# !/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
from datetime import datetime

from app import app, login_manager, db
from app.util.sdn_tools import *
from flask import g, redirect, url_for, abort, render_template, flash, request
from flask.ext.login import login_required, current_user, login_user, logout_user
from werkzeug.utils import secure_filename
from .forms import *
from .models import User, Post

__author__ = 'InG_byr'

@app.before_request
def before_request():
    g.user = current_user


@login_manager.user_loader
def load_user(user_id):
    if user_id == 'None':
        return
    return User.query.get(int(user_id))


@app.route('/')
@app.route('/index')
def index():
    posts = Post.query.all()
    form = MessageForm()
    return render_template('show_entries.html', posts=posts, form=form)


@app.route('/add', methods=['GET', 'POST'])
def add_entry():
    if not current_user.is_authenticated:
        abort(401)
    form = MessageForm()
    if form.validate_on_submit():
        p = Post(body=form.body.data, timestamp=datetime.utcnow(), author=current_user)
        db.session.add(p)
        db.session.commit()
        flash('发布成功')
    else:
        flash('太短了')
    return redirect(url_for('index'))


@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.user_id.data, password=form.password.data).first()
        if user is not None:
            login_user(user)
            flash('登陆成功')
            return redirect(url_for('index'))
        else:
            error = '登陆失败，请重试或联系管理员'
    return render_template('login.html', error=error, form=form)


@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash('用户已注销')
    return redirect(url_for('index'))


@app.route('/upload', methods=['GET', 'POST'])
@login_required
def upload():
    """
    to upload a file to /uploads/
    :return:
    """
    form = PhotoForm()
    if form.validate_on_submit():
        filename = secure_filename(form.presentation.data.filename)
        print(filename)
        form.presentation.data.save(os.getcwd() + '/uploads/' + filename)
        return redirect(url_for('upload', filename=filename))
    else:
        filename = None
    return render_template('upload.html', form=form, filename=filename)


@app.route('/sdn_controller', methods=['GET', 'POST'])
@login_required
def sdn_controller():
    # TODO: handler
    """
    SDN Controller index
    :return:
    """
    form = BlackHostForm()
    form1 = VerifyRoute()
    hosts, m_error = sdn_get_all_host()
    if m_error:
        flash(m_error)
        redirect(url_for('sdn_controller'))
    return render_template('sdn_controller.html', hosts=hosts, enumerate=enumerate,
                           str=str, form=form, form1=form1)


@app.route('/sdn_controller/block_host_by_mac', methods=['POST'])
@login_required
def block_host_by_mac():
    flash('block target')
    form = BlackHostForm()
    if form.validate_on_submit():
        response_data, post_error, get_error, post_data = sdn_manange_black_list(form.mac_address.data, 0)
        if post_error:
            flash(post_error)
        elif get_error:
            flash(get_error)
        else:
            black_list = remote_black_hosts(response_data)
            flash('以下主机已加入黑名单：')
            for host in black_list:
                flash(host['mac'])
    else:
        flash('目标主机不能为空')
    return redirect(url_for('sdn_controller'))


@app.route('/sdn_controller/remove_host_by_mac', methods=['POST'])
@login_required
def remove_host_by_mac():
    flash('remove target')
    form = BlackHostForm()
    if form.validate_on_submit():
        response_data, post_error, get_error, post_data = sdn_manange_black_list(form.mac_address.data, 1)
        if post_error:
            flash(post_error)
        elif get_error:
            flash(get_error)
        else:
            black_list = remote_black_hosts(response_data)
            flash('以下主机已移出黑名单：')
            for host in black_list:
                flash(host['mac'])
    else:
        flash('目标主机不能为空')
    return redirect(url_for('sdn_controller'))


@app.route('/sdn_controller/verify_route', methods=['POST'])
def verify_route():
    form1 = VerifyRoute()
    m_route = ''
    if form1.validate_on_submit():
        mlog.debug('src -> dst: ' + form1.src_host.data + form1.dst_host.data)
        src_host = form1.src_host.data
        dst_host = form1.dst_host.data
        response = sdn_verify_route(src_host, dst_host)

        if not response:
            pass
        else:
            if response['route']:
                # flash('the route is: ' + str(response['route']))
                data = response['route'].split(',')
                raw_route = map(lambda tmp: tmp[1:], data)
                m_route = ''.join(raw_route)


    hosts, m_error = sdn_get_all_host()
    # if m_error:
    #     flash(m_error)
    # return redirect(url_for('sdn_controller'))
    form = BlackHostForm()
    return render_template('sdn_controller.html', hosts=hosts, enumerate=enumerate,
                           str=str, form=form, form1=form1, route=m_route)

